﻿function SetCurrentCategory(cid) {
    $('#CurrentCategory').removeData('cat').val(cid);
}

function BindTreeNode(target, cid, async, complete) {
    $.ajax({
        async: (async === false ? false : true),
        dataType: "json",
        url: "ajax.aspx?action=getcategories&pid=" + cid,
        success: function(data, textStatus) {
            if (data) {
                if (data.Error) {
                    alert(data.Error);
                } else if (data.Result) {
                    target.attr('databind', 'databind');
                    var style = null;
                    var ul = target.find("UL");
                    if (ul) style = ul.attr('style');
                    ul.remove();
                    if (target.is("UL")) {
                        ul = target;
                        ul.empty();
                    } else {
                        ul = $("<ul style='" + style + "'></ul>").appendTo(target);
                    }
                    var i = 0, len = data.Result.length, d, li, a;
                    while (i < len) {
                        d = data.Result[i];
                        li = $("<li></li>").appendTo(ul).attr('cid', d.CategoryId);
                        a = $("<a href='#'>" + d.CategoryName + "</a>").appendTo(li).after($("<ul></ul>"));
                        a.bind('click', d.CategoryId, function(e) { $('#navtree').find('.selectednode').each(function() { $(this).removeClass('selectednode'); }); $(this).parent().addClass('selectednode'); LoadCurrentCategory(e.data); return false; });
                        target.treeview({ add: li });
                        i++;
                    }
                }
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        },
        complete: function() {
            if (complete && typeof (complete) == "function") {
                complete.call(this, target);
            }
        }
    });
}

function LoadCurrentCategory(cid) {
    var oldCId = $('#CurrentCategory').val();
    if (cid == oldCId) {
        return;
    }
    SetCurrentCategory(cid);
    LoadCategory(cid);
    LoadItem(cid);

    $('#CategoryList').empty();
    if (!cid) {
        $('#CurrentCategory').removeData('cat').val('');
        return;
    }
    $.ajax({
        async: true,
        dataType: "json",
        url: "ajax.aspx?action=getcategoryinfo&cid=" + cid,
        beforeSend: function() { $('#tab_current').masklayer('show', { Text: 'Loading Current Category Infomation...' }); },
        success: function(data, textStatus) {
            if (data) {
                data = eval(data);
                if (data.Error) {
                    alert(data.Error);
                } else {
                    BindCurrentCategory(data.Result);
                }
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        },
        complete: function() { $('#tab_current').masklayer('hide'); }
    });
}

function BindCurrentCategory(data) {
    $('#CurrentCategory').data('cat', data);
}

function LoadCategory(cid) {
    $('#CategoryList').empty();
    if (!cid) return;
    $.ajax({
        async: true,
        dataType: "json",
        url: "ajax.aspx?action=getcategories&pid=" + cid,
        beforeSend: function() { $('#tab-category').masklayer('show', { Text: 'Loading Child Categories...' }); },
        success: function(data, textStatus) {
            if (data) {
                if (data.Error) {
                    alert(data.Error);
                } else {
                    BindCategory(data.Result);
                }
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        },
        complete: function() { $('#tab-category').masklayer('hide'); }
    });
}

function BindCategory(data) {
    var target = $('#CategoryList')
    target.empty();
    if (data) {
        var i = 0, len = data.length, d;
        while (i < len) {
            d = data[i];
            var li = $("<li><div><input type='checkbox' /><img title='编辑' tag='folder_modify' src='../css/images/modify.png' /><img title='删除' tag='folder_del' src='../css/images/delete.png' /></div><img src='../css/images/folder.png' /><span>" + d.CategoryName + "</span></li>").appendTo(target);
            li.data('cat', d).attr('catid', d.CategoryId);

            i++;
        }
    }
}

function LoadItem(cid) {
    $('#ItemList').empty();
    try {
        CheckSltAllItemState();
    } catch (e) { }
    if (!cid) return;
    $.ajax({
        async: true,
        dataType: "json",
        url: "ajax.aspx?action=getitems&cid=" + cid,
        beforeSend: function() { $('#tab-item').masklayer('show', { Text: 'Loading Items...' }); },
        success: function(data, textStatus) {
            if (data) {
                if (data.Error) {
                    alert(data.Error);
                } else {
                    BindItem(data.Result);
                }
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        },
        complete: function() { $('#tab-item').masklayer('hide'); }
    });
}

function BindItem(data) {
    var target = $('#ItemList')
    target.empty();
    if (data) {
        var i = 0, len = data.length, d;
        while (i < len) {
            d = data[i];
            var str = "<tr><td><input type='checkbox'/><img src='../css/images/modify.png' title='编辑' tag='item_modify' /><img src='../css/images/delete.png' title='删除' tag='item_del' /></td><td><img class='logo' src='" + d.LogoPath + "' /></td><td>" + d.Title + "</td><td><a target='url_view' href='" + d.LinkUrl + "'>" + d.LinkUrl + "</a></td><td>" + d.AuthorName + "</td><td>" + (new Date(parseInt(d.AddDate.substring(6, 19)))).toLocaleString() + "</td></tr>";
            var tr = $(str).appendTo(target).data('item', d).attr('ItemId', d.ItemId);

            i++;
        }
    }
}

function RefreshItemUI(data) {
    if (!data)
        return;
    $("[ItemId='" + data.ItemId + "']").each(function(index) {
        var target = $(this);
        target.data('item', data);
        target.find(".logo").each(function() { $(this).attr('src', data.LogoPath); });
        $(target.children()[2]).html(data.Title);
        $(target.children()[3]).html(data.LinkUrl);
    });
}

function RefreshCategoryUI(data) {
    if (!data)
        return;
    if (data.CategoryId == $('#CurrentCategory').val()) {
        BindCurrentCategory(data);
    } else {
        $('#CategoryList').find("li[catid=" + data.CategoryId + "]").each(function() {
            $(this).data('cat', data);
            $(this).find("span").html(data.CategoryName);
        });
    }
}

function DeleteItemsUI(idArr) {
    if (!idArr)
        return;
    var i = 0, len = idArr.length, id;
    while (i < len) {
        id = idArr[i];
        $("[ItemId='" + id + "']").each(function() {
            $(this).remove();
        });
        i++;
    }
}

function RefreshUncheckedItems() {
    var target = $('#UnchectedItemList')
    target.empty();
    CheckSltAllUnchkItemState();
    $.ajax({
        async: true,
        dataType: "json",
        url: "ajax.aspx?action=getuncheckeditems",
        beforeSend: function() { $('#tab-uncheckeditem').masklayer('show', { Text: 'Loading Items...' }); },
        success: function(data, textStatus) {
            if (data) {
                if (data.Error) {
                    alert(data.Error);
                } else {
                    var i = 0, len = data.Result.length, d;
                    while (i < len) {
                        d = data.Result[i];
                        var str = "<tr><td><input type='checkbox'/><img tag='item_modify' src='../css/images/modify.png' title='编辑' /><img tag='item_chk' src='../css/images/check.png' title='通过审核' /><img tag='item_del' src='../css/images/delete.png' title='删除' /></td><td><img class='logo' src='" + d.LogoPath + "' /></td><td>" + d.Title + "</td><td><a target='url_view' href='" + d.LinkUrl + "'>" + d.LinkUrl + "</a></td><td>" + d.AuthorName + "</td><td>" + (new Date(parseInt(d.AddDate.substring(6, 19)))).toLocaleString() + "</td></tr>";
                        var tr = $(str).appendTo(target).data('item', d).attr('itemid', d.ItemId);

                        i++;
                    }
                }
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        },
        complete: function() { $('#tab-uncheckeditem').masklayer('hide'); }
    });
}

function Jump2Node(cId) {
    if (!cId)
        return;
    var hash = [cId];
    $('#content').masklayer('show');
    if ($('#navtree').find("li[cid=" + cId + "]").length > 0) {
        var li = $($('#navtree').find("li[cid=" + cId + "]")[0]);
        while (!li.parent().is('#navtree')) {
            li = li.parent().parent();
            hash.push(li.attr('cid'));
        }
    } else {
        $.ajax({
            url: "ajax.aspx?action=getrecursiveparents&cid=" + cId,
            async: false,
            dataType: "json",
            beforeSend: function() {
            },
            success: function(data) {
                if (data.Result) {
                    data = eval(data.Result);
                    data.pop(); //去掉自身
                    while (data.length > 0) {
                        hash.push((data.pop()).CategoryId);
                    }
                }
            }
        });
    }
    var id = hash.pop();
    while (hash && hash.length > 0) {
        $('#navtree').find("li[cid=" + id + "]").each(function() {
            var li = $(this);
            if (!li.is('[databind]')) {
                BindTreeNode(li, id, false);
            }
            if (this.className.indexOf('expandable') > -1) {
                li.children(".hitarea").trigger('click');
            }
        });
        id = hash.pop();
    }
    $('#navtree').find("li[cid=" + id + "]").children("a").trigger('click');
    $('#content').masklayer('hide');
}